package org.example.booksystem.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.booksystem.constants.Constants;
import org.example.booksystem.moudel.*;
import org.example.booksystem.service.BookInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookInfoController {

    @Autowired
    private BookInfoService service;

    @RequestMapping("/getListByPage")
    public Result<PageResult<BookInfo>> getListByPage(PageRequest pageRequest) {

        log.info("根据页码获取数据{}", pageRequest);
        if (pageRequest.getCurrentPage() < 1) {
            log.error("页码不合法");
            return Result.fail("参数不合法");
        }

        PageResult<BookInfo> result = service.getBookListByPage(pageRequest);

        return Result.success(result);
    }


    @RequestMapping(value = "/addBook" , produces = "application/json")
    public String addBook(BookInfo bookInfo) {
        String check = service.insertBook(bookInfo);
        return check;
    }

    @RequestMapping("queryBookById")
    public Result<BookInfo> queryBookById(Integer bookId) {
        long l1 = System.currentTimeMillis();

        if (bookId == null || bookId < 1) {
            log.error("bookId不合法");
            return Result.fail("参数非法");
        }
        long l2 = System.currentTimeMillis();

        BookInfo bookInfo = service.getBookById(bookId);

        long l3 = System.currentTimeMillis();

        return Result.success(bookInfo);
    }

    @RequestMapping("/updateBook")
    public boolean updateBook(BookInfo bookInfo) {
        log.info("修改图书{}", bookInfo);
        return service.updateBook(bookInfo);
    }

    @RequestMapping("/batchDelete")
    public boolean batchDelete(@RequestParam List<Integer> ids) {
        log.info("批量删除{}", ids);
        try {
            Integer result = service.batchDelete(ids);
            if (result <= 0) {
                return false;

            }
            return true;
        } catch (Exception e) {
            log.error("批量删除失败{},{}", ids, e);
            return false;
        }
    }

}
